import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useCouponsStore = defineStore('coupons', () => {
  // 优惠券列表
  const couponsList = ref([])
  
  // 优惠券数量
  const couponsCount = computed(() => couponsList.value.length)
  
  // 可用优惠券数量
  const availableCouponsCount = computed(() => 
    couponsList.value.filter(coupon => coupon.status === 'available').length
  )
  
  // 已使用优惠券数量
  const usedCouponsCount = computed(() => 
    couponsList.value.filter(coupon => coupon.status === 'used').length
  )
  
  // 已过期优惠券数量
  const expiredCouponsCount = computed(() => 
    couponsList.value.filter(coupon => coupon.status === 'expired').length
  )
  
  // 获取优惠券
  const getCouponById = (couponId) => {
    return couponsList.value.find(coupon => coupon.id === couponId)
  }
  
  // 使用优惠券
  const useCoupon = (couponId) => {
    const coupon = getCouponById(couponId)
    if (coupon && coupon.status === 'available') {
      coupon.status = 'used'
      coupon.usedTime = new Date().toISOString()
      saveToLocalStorage()
      return true
    }
    return false
  }
  
  // 获取可用优惠券
  const getAvailableCoupons = () => {
    return couponsList.value.filter(coupon => coupon.status === 'available')
  }
  
  // 获取已使用优惠券
  const getUsedCoupons = () => {
    return couponsList.value.filter(coupon => coupon.status === 'used')
  }
  
  // 获取已过期优惠券
  const getExpiredCoupons = () => {
    return couponsList.value.filter(coupon => coupon.status === 'expired')
  }
  
  // 按状态筛选优惠券
  const getCouponsByStatus = (status) => {
    if (!status) return couponsList.value
    return couponsList.value.filter(coupon => coupon.status === status)
  }
  
  // 搜索优惠券
  const searchCoupons = (keyword) => {
    if (!keyword) return couponsList.value
    return couponsList.value.filter(coupon => 
      coupon.name.toLowerCase().includes(keyword.toLowerCase()) ||
      coupon.description.toLowerCase().includes(keyword.toLowerCase())
    )
  }
  
  // 保存到本地存储
  const saveToLocalStorage = () => {
    try {
      localStorage.setItem('enba-coupons', JSON.stringify(couponsList.value))
    } catch (error) {
      console.error('保存优惠券数据失败:', error)
    }
  }
  
  // 从本地存储加载
  const loadFromLocalStorage = () => {
    try {
      const stored = localStorage.getItem('enba-coupons')
      if (stored) {
        couponsList.value = JSON.parse(stored)
      }
    } catch (error) {
      console.error('加载优惠券数据失败:', error)
      couponsList.value = []
    }
  }
  
  // 初始化默认优惠券数据
  const initDefaultCoupons = () => {
    if (couponsList.value.length === 0) {
      const defaultCoupons = [
        {
          id: 'c001',
          name: '新人专享券',
          type: 'discount',
          value: 50,
          minAmount: 200,
          description: '新人专享，满200减50',
          startDate: new Date(Date.now() - 86400000 * 30).toISOString(), // 30天前开始
          endDate: new Date(Date.now() + 86400000 * 60).toISOString(), // 60天后过期
          status: 'available',
          category: '新人专享',
          usageLimit: 1,
          usedCount: 0
        },
        {
          id: 'c002',
          name: '满减优惠券',
          type: 'discount',
          value: 30,
          minAmount: 150,
          description: '满150减30，全场通用',
          startDate: new Date(Date.now() - 86400000 * 15).toISOString(), // 15天前开始
          endDate: new Date(Date.now() + 86400000 * 45).toISOString(), // 45天后过期
          status: 'available',
          category: '满减券',
          usageLimit: 3,
          usedCount: 0
        },
        {
          id: 'c003',
          name: '9折优惠券',
          type: 'percentage',
          value: 0.9,
          minAmount: 100,
          description: '全场9折，满100可用',
          startDate: new Date(Date.now() - 86400000 * 7).toISOString(), // 7天前开始
          endDate: new Date(Date.now() + 86400000 * 23).toISOString(), // 23天后过期
          status: 'available',
          category: '折扣券',
          usageLimit: 2,
          usedCount: 0
        },
        {
          id: 'c004',
          name: '免邮券',
          type: 'shipping',
          value: 0,
          minAmount: 0,
          description: '全场免邮费',
          startDate: new Date(Date.now() - 86400000 * 5).toISOString(), // 5天前开始
          endDate: new Date(Date.now() + 86400000 * 25).toISOString(), // 25天后过期
          status: 'used',
          category: '免邮券',
          usageLimit: 1,
          usedCount: 1,
          usedTime: new Date(Date.now() - 86400000 * 2).toISOString() // 2天前使用
        },
        {
          id: 'c005',
          name: '限时优惠券',
          type: 'discount',
          value: 20,
          minAmount: 100,
          description: '限时优惠，满100减20',
          startDate: new Date(Date.now() - 86400000 * 60).toISOString(), // 60天前开始
          endDate: new Date(Date.now() - 86400000 * 30).toISOString(), // 30天前过期
          status: 'expired',
          category: '限时券',
          usageLimit: 1,
          usedCount: 0
        }
      ]
      couponsList.value = defaultCoupons
      saveToLocalStorage()
    }
  }
  
  // 检查优惠券是否可用
  const isCouponAvailable = (couponId) => {
    const coupon = getCouponById(couponId)
    if (!coupon) return false
    
    const now = new Date()
    const startDate = new Date(coupon.startDate)
    const endDate = new Date(coupon.endDate)
    
    return coupon.status === 'available' && 
           now >= startDate && 
           now <= endDate && 
           coupon.usedCount < coupon.usageLimit
  }
  
  // 获取优惠券显示值
  const getCouponDisplayValue = (coupon) => {
    if (coupon.type === 'discount') {
      return `¥${coupon.value}`
    } else if (coupon.type === 'percentage') {
      return `${Math.round((1 - coupon.value) * 100)}折`
    } else if (coupon.type === 'shipping') {
      return '免邮'
    }
    return ''
  }
  
  return {
    couponsList,
    couponsCount,
    availableCouponsCount,
    usedCouponsCount,
    expiredCouponsCount,
    getCouponById,
    useCoupon,
    getAvailableCoupons,
    getUsedCoupons,
    getExpiredCoupons,
    getCouponsByStatus,
    searchCoupons,
    saveToLocalStorage,
    loadFromLocalStorage,
    initDefaultCoupons,
    isCouponAvailable,
    getCouponDisplayValue
  }
})
